package com.wangsd.web.sys.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangsd.web.sys.entity.Area;
import com.wangsd.web.sys.mapper.AreaMapper;
import com.wangsd.web.sys.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-10-28
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    @Autowired
    AreaMapper areaMapper;

    @Override
    public List<Area> selectByParentId(String parentId) {
        QueryWrapper<Area> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<Area> areas = areaMapper.selectList(queryWrapper);
        return areas;
    }

    @Override
    public JSONArray selectAllArea() {
        List<Area> areas = areaMapper.selectList(new QueryWrapper<Area>());
        Map<String, List<Area>> collect = areas.stream().collect(Collectors.groupingBy(Area::getParentId));
        List<Area> p_area = collect.get("100000");
        JSONArray p_array = new JSONArray();
        for (Area area : p_area) {
            JSONObject p_object = new JSONObject();
            p_object.put("value", area.getId());
            p_object.put("label", area.getName());
            List<Area> c_list = collect.get(area.getId());
            JSONArray c_array = new JSONArray();
            if (c_list != null) {
                for (Area c_area : c_list) {
                    JSONObject c_object = new JSONObject();
                    c_object.put("value", c_area.getId());
                    c_object.put("label", c_area.getName());
                    List<Area> a_list = collect.get(c_area.getId());
                    if (a_list != null) {
                        JSONArray a_array = new JSONArray();
                        for (Area a_area : a_list) {
                            JSONObject a_object = new JSONObject();
                            a_object.put("value", a_area.getId());
                            a_object.put("label", a_area.getName());
                            a_array.add(a_object);
                        }
                        c_object.put("children", a_array);
                    }
                    c_array.add(c_object);
                }
                p_object.put("children", c_array);
            }
            p_array.add(p_object);
        }
        return p_array;
    }
}
